﻿using System;
using System.Collections;
using System.Data;
using System.IO;
using System.Windows.Forms;
using System.Xml;
using SharePoint.ImportExport.Core;

namespace CodePlex.ExtractedDataReorganizer
{
    public partial class frmCreateListFromXml : Form
    {
        DataSet ds;
        SharePoint.ImportExport.Core.Site ParentSite;
        string DirName=String.Empty;
        public frmCreateListFromXml(string dirName, SharePoint.ImportExport.Core.Site parentSite)
        {
            InitializeComponent();
            DirName = dirName;
            this.txtFileName.Text = dirName + "\\";
            this.ParentSite = parentSite;
            this.txtUrl.Text="http://www.msdomino.net/orders.nsf/xmlexport?open&orders.nsf!view!complete customer orders!orderID!customerID!OrderDate!Freight!ShipAddress!shipcity!ShipCountry!$UpDatedBy!$Revisions";
        }

        private void frmCreateListFromXml_Load(object sender, EventArgs e)
        {
            ds = new DataSet();
            DataGridViewComboBoxColumn cbCol = (DataGridViewComboBoxColumn)this.dataGridView1.Columns[2];
            cbCol.Items.Add(FieldType.Boolean.ToString());
            cbCol.Items.Add(FieldType.Choice.ToString());
            cbCol.Items.Add(FieldType.Currency.ToString());
            cbCol.Items.Add(FieldType.DateTime.ToString());
            cbCol.Items.Add(FieldType.Integer.ToString());
            cbCol.Items.Add(FieldType.Note.ToString());
            cbCol.Items.Add(FieldType.Number.ToString());
            cbCol.Items.Add(FieldType.Text.ToString());
            cbCol.Items.Add(FieldType.URL.ToString());
            cbCol.Items.Add(FieldType.User.ToString());

        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            if (ds != null)
            {
                ds.Clear();
                ds.Dispose();
                ds = null;

            }

        }

        private void btnReadXml_Click(object sender, EventArgs e)
        {
            try
            {
                using (XmlTextReader xTextReader = new XmlTextReader(this.txtUrl.Text))
                {
                    if (ds == null)
                    {
                        ds = new DataSet();
                    }

                    ds.ReadXml(xTextReader);
                    Directory.CreateDirectory(this.txtFileName.Text + ds.Tables[0].TableName);
                    this.txtFileName.Text += ds.Tables[0].TableName+"\\items.xml";


                    foreach (DataColumn col in ds.Tables[0].Columns)
                    {
                        int row = this.dataGridView1.Rows.Add();
                        DataGridViewCell currentCell = dataGridView1.Rows[row].Cells[0];
                        currentCell.Value = col.Caption;

                    }

                }

            }
            catch (Exception Ex)
            {
            }

        }

        private void btnCreateListing_Click(object sender, EventArgs e)
        {
            List list = new List();
            list.BaseTemplate = "GenericList";
            list.DataType = ListType.Library;
            list.Name = ds.Tables[0].TableName;
            list.Operation = Verb.Create;
            list.Template = ds.Tables[0].TableName;

            ListOfItems listOfItems = new ListOfItems();
            ItemType type = new ItemType();
            type.Name = ds.Tables[0].TableName;
            bool fieldsAdded = false;

            SharePoint.ImportExport.Core.View view = new SharePoint.ImportExport.Core.View();
            view.Name = list.Name;

            foreach (DataRow row in ds.Tables[0].Rows)
            {
                Item item = new Item();
                int colCount = 0;
                foreach (DataGridViewRow dRow in this.dataGridView1.Rows)
                {
                    bool bUse=false;
                    try
                    {
                        bUse = (bool)dRow.Cells["Use"].Value;
                    }
                    catch
                    {
                    }
                    
                    if (bUse)
                    {
                        ItemProperty prop = new ItemProperty();
                        if(dRow.Cells["SharePointField"].Value != null)
                        {
                            prop.Name = dRow.Cells["SharePointField"].Value.ToString();
                        }
                        else
                        {
                            prop.Name = dRow.Cells["Field"].Value.ToString();
                        }

                        prop.DataType = FieldType.Text;
                        try
                        {
                            prop.DataType = (FieldType)Enum.Parse(typeof(FieldType), dRow.Cells["DataType"].Value.ToString());
                        }
                        catch
                        {
                        }

                        prop.Value = row[colCount].ToString();
                        item.Fields.Add(prop);
                        if (!fieldsAdded)
                        {
                            SharePoint.ImportExport.Core.Field field = new Field();
                            field.DisplayName = prop.Name;
                            field.ExtendedType = prop.DataType;
                            field.Name = field.DisplayName;
                            field.AddToDefaultView = true;
                            list.Fields.Add(field);

                            view.ViewFields.Add(field.Name);
                        }
                    }
                    colCount++;

                    
                    //try
                    //{
                    //    prop.Value = propertyNode.FirstChild.Value;
                    //}
                    //catch (Exception Ex)
                    //{
                    //}

                    //

                }


                type.Items.Add(item);
                fieldsAdded = true;
            }

            listOfItems.ItemTypes.Add(type);


            listOfItems.Serialize(this.txtFileName.Text);
            list.RelativeitemXML = this.txtFileName.Text.Substring(this.DirName.Length);
            list.Views.Add(view);
            ParentSite.Lists.Add(list);

        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            if (ds != null)
            {
                ds.Clear();
                ds.Dispose();
                ds = null;

            }

        }

        private void btnResolveUsers_Click(object sender, EventArgs e)
        {
            Hashtable ht = new Hashtable();
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                int colCount = 0;
                foreach (DataGridViewRow dRow in this.dataGridView1.Rows)
                {
                    if (dRow.Cells["DataType"].Value != null)
                    {
                        if (FieldType.User == (FieldType)Enum.Parse(typeof(FieldType), dRow.Cells["DataType"].Value.ToString()))
                        {
                            string userName = row[colCount].ToString();
                            if (!userName.Contains("\\"))
                            {
                                if (ht.ContainsKey(userName))
                                {
                                    row[colCount] = ht[userName];

                                }
                                else
                                {
                                    frmRename frm = new frmRename();
                                    frm.txtOldName.Text = userName;
                                    frm.Text = "Rename user";
                                    if (DialogResult.OK == frm.ShowDialog())
                                    {
                                        ht.Add(userName, frm.txtNewName.Text);
                                        row[colCount] = frm.txtNewName.Text;
                                    }
                                }

                            }
                        }
                    }
                    colCount++;
                }

            }
        }
    }
}
